<?php

namespace app\api\controller\v44;

use app\api\controller\v2\Auth;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\lib\Util;
use app\common\model\Recode;
use think\response\Json;

class AiUserChat extends Auth
{
    public function synastryChoose()
    {
        $rid2 = input('rid2/d', 0);
        $chatDetailId = input('chat_id/d', 0);
        $status = input('status/d', 0);

        if (Util::commentCheck($this->user['id'], ['action' => 'synastryChoose', 'chat_id' => $chatDetailId, 'status' => $status, 'rid2' => $rid2], 2) && (int)$this->user['id'] != 12346744)
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (!$chatDetailId || !in_array($status, [1, 2, 3], true) || ($status === 2 && !$rid2))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetailInfo || $chatDetailInfo['uid'] !== $this->user['id'] || !isset($chatDetailInfo['extend']['recommend_synastry']))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($chatDetailInfo['extend']['recommend_synastry']['status'] !== 0)
        {
            return show(config('code.error'), '服务异常，请刷新后再试～');
        }
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        $dataList = [];
        switch ($status)
        {
            case 1: // 取消合盘 继续解答
                $chatDetailInfo['extend']['recommend_synastry']['status'] = 2;  // 不合盘状态
                if (isset($chatDetailInfo['extend']['recommend_synastry']['not_combining_has_answer']) && $chatDetailInfo['extend']['recommend_synastry']['not_combining_has_answer'])
                {   // 暂不合盘继续解答 有流式答案
                    if ($numData['res_num'] <= 0)
                    {   // 会话次数 用尽
                        return show(config('code.error'), '今日提问机会用尽，明天再来吧～');
                    }
                    // 扣除次数
                    $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
                    $insertData = [
                        'chat_id' => $chatDetailInfo['chat_id'],
                        'uid' => $this->user['id'],
                        'rid' => $chatDetailInfo['rid'],
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => '', // 提问问题
                        'data_type' => 1,   // 1=>普通消息  2=>结果消息 3=>扩展消息
                        'extend' => [
                            'result_type' => 2,
                            'model_name' => $chatDetailInfo['extend']['model_name'],
                            'recommend_good' => $chatDetailInfo['extend']['recommend_good'],
                            'is_valid' => 1,    // 有效答案
                            'stream' => 1,
                            'sas' => $chatDetailInfo['extend']['sas'],
                            'sact' => $chatDetailInfo['extend']['sact'],
                        ],  //  澄清数据
                        'result_data' => '',
                        'num_type' => $numData['use_type'], // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'option_id' => '',
                        'pid' => $chatDetailId, // 待更新
                        'create_time' => $this->request->time(),
                    ];
                } else
                {   // 没有 流式答案
                    $insertData = [
                        'chat_id' => $chatDetailInfo['chat_id'],
                        'uid' => $this->user['id'],
                        'rid' => $chatDetailInfo['rid'],
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => '', // 提问问题
                        'data_type' => 1,   // 1=>普通消息  2=>结果消息 3=>扩展消息
                        'extend' => [
                            'result_type' => 2,
                            'model_name' => $chatDetailInfo['extend']['model_name'],
                            'recommend_good' => $chatDetailInfo['extend']['recommend_good'],
                            'is_valid' => 0,
                            'stream' => 0,
                            'sas' => $chatDetailInfo['extend']['sas'],
                            'sact' => $chatDetailInfo['extend']['sact'],
                        ],  //  澄清数据
                        'result_data' => '',
                        'num_type' => 0, // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                        'option_id' => '',
                        'pid' => $chatDetailId, // 待更新
                        'create_time' => $this->request->time(),
                    ];
                }
                break;
            case 2: // 确认合盘 进行解答
                if ($rid2 === $chatDetailInfo['rid'])
                {
                    return show(config('code.error'), '服务异常，同一个档案不能进行合盘');
                }
                $recodeInfo = (new Recode())->getRecode(['id' => $chatDetailInfo['rid']]);
                $recodeInfo2 = (new Recode())->getRecode(['id' => $rid2]);
                if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'] || $recodeInfo2['status'] != 1)
                {
                    return show(config('code.error'), '服务异常，档案不存在');
                }
                $chatDetailInfo['extend']['recommend_synastry']['status'] = 1;  // 不合盘状态  // 0=>等待用户是否合盘 1=>合盘选择成功 2=>暂不合盘继续解答
                $chatDetailInfo['extend']['recommend_synastry']['rid2'] = $rid2;
                $chatDetailInfo['extend']['recommend_synastry']['avatar2'] = $recodeInfo2['avatar'] ?? '';
                $chatDetailInfo['extend']['recommend_synastry']['name2'] = $recodeInfo2['name'] ?? '';
                if ($numData['res_num'] <= 0)
                {   // 会话次数 用尽
                    return show(config('code.error'), '今日提问机会用尽，明天再来吧～');
                }
                // 扣除次数
                $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
                $hzChatRecordModel = new HzChatRecord();
                $hzChatRecordModel->updateData($chatDetailInfo['chat_id'], $this->user['id'], ['rid2' => $rid2]);

                $parentData = $hzChatRecordDetailsModel->getInfoById($chatDetailInfo['pid'], ['content']);
                $insertData = [
                    'chat_id' => $chatDetailInfo['chat_id'],
                    'uid' => $this->user['id'],
                    'rid' => $chatDetailInfo['rid'],
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => '', // 提问问题
                    'data_type' => 1,   // 1=>普通消息  2=>结果消息 3=>扩展消息
                    'extend' => [
                        'result_type' => 2,
                        'model_name' => $chatDetailInfo['extend']['model_name'],
                        'recommend_good' => $chatDetailInfo['extend']['recommend_good'],
                        'is_valid' => 1,
                        'stream' => 1,
                        'sas' => $chatDetailInfo['extend']['sas'],
                        'sact' => $chatDetailInfo['extend']['sact'],
                        'synastry_result' => [
                            'rid' => $chatDetailInfo['rid'],
                            'rname1' => $recodeInfo['name'],
                            'rid2' => $rid2,
                            'rname2' => $recodeInfo2['name'],
                            'question' => $parentData['content'] ?? '',
                        ],
                    ],  //  澄清数据
                    'result_data' => '',
                    'num_type' => $numData['use_type'], // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                    'option_id' => '',
                    'pid' => $chatDetailId, // 待更新
                    'create_time' => $this->request->time(),
                ];
                break;
            default: // 取消合盘 停止解答
                $chatDetailInfo['extend']['recommend_synastry']['status'] = 2;  // 不合盘状态
        }
        $dataList[] = $chatDetailInfo;

        if (isset($insertData) && $insertData)
        {   // 新增 信息
            $res = $hzChatRecordDetailsModel->SaveData($chatDetailInfo['chat_id'], [$insertData]);

            $dataList[] = $res[0];
        }

        // 更新 合盘 状态
        $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
            'extend' => json_encode($chatDetailInfo['extend'], JSON_UNESCAPED_UNICODE),
        ]);

        $resData = $hzChatRecordDetailsModel->dataListResert($dataList, true);

        $resData[0]['create_time'] = '';
        $resData[0]['stream'] = 0;
        if (isset($resData[1]))
        {
            $resData[1]['stream'] = 0;
        }
        if (isset($resData[1]) && $resData[1]['is_stream_reload'] === 1)
        {
            $resData[1]['is_stream_reload'] = 0;
            $resData[1]['content'] = '';
            $resData[1]['stream'] = 1;
        }

        return show(config('code.success'), '请求成功', [
            'num' => $numData['res_num'],
            'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
            'list' => $resData,
        ]);
    }

    /**
     * 档案 澄清 选择
     * @return Json
     * @throws \Exception
     */
    public function recodeChoose()
    {
        $rid = input('rid/d', 0);
        $chatDetailId = input('chat_id/d', 0);
        $status = input('status/d', 0);
        $type = input('type/d', 0);

        if (Util::commentCheck($this->user['id'], ['action' => 'synastryChoose', 'chat_id' => $chatDetailId, 'status' => $status, 'rid' => $rid, 'type' => $type], 2) && (int)$this->user['id'] != 12346744)
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (!$chatDetailId || !in_array($status, [2, 3], true) || ($status === 2 && (!$rid || !in_array($type, [1, 2], true))))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!Util::IsIos() && Util::checkAppVersion('2.10.6') === '小')
        {   // 安卓  并且 版本 低于2.10.6
            $chatDetailId += 1000000;
        }
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $chatDetailInfo = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetailInfo || $chatDetailInfo['uid'] !== $this->user['id'] || !isset($chatDetailInfo['extend']['recode_choose']))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($chatDetailInfo['extend']['recode_choose']['status'] !== 0)
        {
            return show(config('code.error'), '服务异常，请刷新后再试～');
        }
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        $dataList = [];
        if ($status === 2)
        {   // 解答
            $recodeInfo = (new Recode())->getRecode(['id' => $rid]);
            if (!$recodeInfo || $recodeInfo['uid'] != $this->user['id'] || $recodeInfo['status'] != 1)
            {
                return show(config('code.error'), '服务异常，档案不存在');
            }
            $chatDetailInfo['extend']['recode_choose']['status'] = 1;  // 解答状态
            $chatDetailInfo['extend']['recode_choose']['rid'] = $rid;
            $chatDetailInfo['extend']['recode_choose']['avatar'] = $recodeInfo['avatar'];
            $chatDetailInfo['extend']['recode_choose']['name'] = $recodeInfo['name'];
            if ($numData['res_num'] <= 0)
            {   // 会话次数 用尽
                return show(config('code.error'), '今日提问机会用尽，明天再来吧～');
            }
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData);
            if ($rid != $chatDetailInfo['rid'])
            {
                $hzChatRecordModel = new HzChatRecord();
                $hzChatRecordModel->updateData($chatDetailInfo['chat_id'], $this->user['id'], ['rid2' => $rid]);
            }

            $parentData = $hzChatRecordDetailsModel->getInfoById($chatDetailInfo['pid'], ['content']);

            $insertData = [
                'chat_id' => $chatDetailInfo['chat_id'],
                'uid' => $this->user['id'],
                'rid' => $chatDetailInfo['rid'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '', // 提问问题
                'data_type' => 1,   // 1=>普通消息  2=>结果消息 3=>扩展消息
                'extend' => [
                    'result_type' => 2,
                    'model_name' => $chatDetailInfo['extend']['model_name'],
                    'recommend_good' => $chatDetailInfo['extend']['recommend_good'],
                    'is_valid' => 1,
                    'stream' => 1,
                    'sas' => $chatDetailInfo['extend']['sas'],
                    'sact' => $chatDetailInfo['extend']['sact'],
                    'recode_choose_result' => [
                        'rid' => $rid,
                        'question' => $parentData['content'] ?? '',
                    ],
                ],  //  澄清数据
                'result_data' => '',
                'num_type' => $numData['use_type'], // 使用类型0=>不扣次数 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                'option_id' => '',
                'pid' => $chatDetailId, // 待更新
                'create_time' => $this->request->time(),
            ];
        } else
        {   // 取消解答
            $chatDetailInfo['extend']['recode_choose']['status'] = 2;  // 不解答状态
        }
        $dataList[] = $chatDetailInfo;

        if (isset($insertData) && $insertData)
        {   // 新增 信息
            $res = $hzChatRecordDetailsModel->SaveData($chatDetailInfo['chat_id'], [$insertData]);

            $dataList[] = $res[0];
        }

        // 更新 合盘 状态
        $hzChatRecordDetailsModel->UpdateData($chatDetailId, [
            'extend' => json_encode($chatDetailInfo['extend'], JSON_UNESCAPED_UNICODE),
        ]);

        $resData = $hzChatRecordDetailsModel->dataListResert($dataList, true);

        $resData[0]['create_time'] = '';
        $resData[0]['stream'] = 0;
        if (isset($resData[1]))
        {
            $resData[1]['stream'] = 0;
        }
        if (isset($resData[1]) && $resData[1]['is_stream_reload'] === 1)
        {
            $resData[1]['is_stream_reload'] = 0;
            $resData[1]['content'] = '';
            $resData[1]['stream'] = 1;
        }

        return show(config('code.success'), '请求成功', [
            'num' => $numData['res_num'],
            'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
            'list' => $resData,
        ]);
    }
}